<!-- 课程活动 -->
<template>
  <div>
    <div  id="chart" ref="chartContainer" class="w-full h-[450px]"></div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  name: "Activity",
  data() {
    return {
      data: {
        missionType: this.$store.state.mission,
        studentClassId: this.$store.state.current
      },
      rank: [],
      chart: null,
    };
  },
  computed: {
    studentClassId() {
      return this.$store.state.current;
    },
    missionType() {
      return this.$store.state.mission;
    }
  },
  mounted() {
    this.fetchData();
  },
  watch: {
    studentClassId() {
      this.data.studentClassId = this.studentClassId;
      this.fetchData();
    },
    missionType() {
      this.data.missionType = this.missionType;
      this.fetchData();
    }
  },
  methods: {
    fetchData() {
      axios.post("/group/stats", this.data)
        .then(response => {
          if (response.data && response.data.data) {
            console.log(1);
            this.rank = response.data.data;
            if (this.rank.group && Array.isArray(this.rank.group)) {
              this.rank.group = this.rank.group.map(group => {
                return group !== null ? `第${group}组` : '未知组';
              });
            }
            this.initChart();
          }
        })
        .catch(error => {
          console.error('请求失败', error);
        });
    },
    initChart() {
      // 销毁现有图表实例
      // if (this.chart) {
      //   this.chart.dispose();
      // }

      // 假设rank数据格式如下，根据实际情况调整
      // 这里使用固定数据作为示例，实际应从this.rank中提取
      const xjcs = this.rank.flower;
      const xjgls = this.rank.during;
      const myData1 = this.rank.group;

      // 分别计算flower和during的最大值
      const maxXjcs = Math.ceil(Math.max(...xjcs));
      const maxXjgls = Math.ceil(Math.max(...xjgls));

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          textStyle: { color: "#fff", fontSize: 12 },
          confine: true,
          backgroundColor: "rgba(17,95,182,0.5)",
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(param => {
              if (param.seriesName === '课中成绩') {
                result += param.seriesName + '：' + param.value + '<br/>';
              } else if (param.seriesName === '小红花个数') {
                result += param.seriesName + '：' + param.value;
              }
            });
            return result;
          }
        },
        legend: {
          top: "4%",
          left: "center",
          itemWidth: 18,
          itemHeight: 10,
          itemGap: 30,
          textStyle: { fontSize: 12, color: "#fff", padding: [0, 0, 0, 10] },
        },
        grid: {
          top: "18%",
          left: "4%",
          right: "3%",
          bottom: "2%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: myData1,
            axisTick: { show: false, alignWithLabel: true },
            axisLine: { lineStyle: { color: "#1C82C5" } },
            axisLabel: {
              interval: 0,
              margin: 10,
              textStyle: { fontSize: 14, color: "#fff" },
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "个数",
            fontSize: 16,
            splitNumber: 5,
            show: true,
            nameTextStyle: { color: "#fff", fontSize: 12, align: "center", padding: [0, 28, 0, 0] },
            axisLabel: {
              formatter: "{value}",
              textStyle: { fontSize: 14, color: "#fff", lineHeight: 16 },
            },
            axisLine: { lineStyle: { color: "#1C82C5" } },
            axisTick: { show: false },
            splitLine: {
              show: true,
              lineStyle: { color: "rgba(28, 130, 197, .3)", type: "dashed" },
            },
            max: maxXjcs
          },
          {
            name: "分数",
            splitNumber: 5,
            show: true,
            nameTextStyle: { color: "#fff", fontSize: 12, align: "center", padding: [0, 0, 0, 25] },
            axisLabel: {
              show: true,
              fontSize: 14,
              color: "#fff"
            },
            axisLine: { lineStyle: { color: "#1C82C5" } },
            axisTick: { show: false },
            splitLine: {
              show: false
            },
            max: maxXjgls
          },
        ],
        series: [
          {
            name: "课中成绩",
            type: "line",
            yAxisIndex: 1,
            showSymbol: true,
            symbolSize: 8,
            lineStyle: { color: "#00FFF686" },
            itemStyle: { color: "#00FFF686", borderColor: "#00FFF686", borderWidth: 2 },
            label: { show: true, position: "top", textStyle: { fontSize: 14, color: "#91CDFE" } },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 1, color: '#00FFF686' },
                  { offset: 0.25, color: '#00FFF600' }
                ]
              }
            },
            data: xjgls,
          },
          {
            name: "小红花个数",
            type: "bar",
            barWidth: "12",
            data: xjcs,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: "rgba(9, 63, 109, 1)" },
                  { offset: 1, color: "rgba(1, 166, 252, 1)" }
                ]
              },
              borderColor: "#3681FF",
            },
          },
        ],
      };

      this.chart = echarts.init(this.$refs.chartContainer);
      this.chart.setOption(option);

      // 添加图例选择事件监听
      this.chart.on('legendselectchanged', (params) => {
        const isBarVisible = params.selected['小红花个数'];
        const isLineVisible = params.selected['课中成绩'];
        const option = this.chart.getOption();
        option.yAxis[0].show = isBarVisible;
        option.yAxis[1].show = isLineVisible;
        this.chart.setOption(option);
      });

      // 添加响应式处理
      window.addEventListener('resize', this.resizeChart);
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      window.removeEventListener('resize', this.resizeChart);
    }
  }
};
</script>
<style>
#chart {
  width: 100%;
  height: 450px;
}
</style>